package net.cnki.sunny.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import net.cnki.sunny.base.BaseController;
import net.cnki.sunny.common.ResultVO;
import net.cnki.sunny.model.dto.UserDTO;
import net.cnki.sunny.model.entity.User;
import net.cnki.sunny.service.UserService;
import net.cnki.sunny.validate.BeanValidation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @GetMapping("/user/list")
    public List<User> getUserList() {
        return userService.getUserList();
    }

    @PostMapping("/user")
    public ResultVO addUser(@RequestBody @Validated(value = BeanValidation.SecondGroup.class) UserDTO userDTO) {
        User user = new User();
        BeanUtil.copyProperties(userDTO, user, CopyOptions.create().ignoreNullValue());
        userService.addUser(user);
        return new ResultVO().success();
    }

    @PutMapping("/user")
    public ResultVO modifyUser(@RequestBody @Validated(value = BeanValidation.ThirdGroup.class) UserDTO userDTO) {
        User user = new User();
        BeanUtil.copyProperties(userDTO, user, CopyOptions.create().ignoreNullValue());
        userService.modifyUser(user);
        return new ResultVO().success();
    }

    @DeleteMapping("/user/{id}")
    public ResultVO deleteUser(@PathVariable("id") Integer id) {
        userService.deleteUser(id);
        return new ResultVO().success();
    }

    @GetMapping("/users")
    public ResultVO getUserList(UserDTO userDTO) {
        return new ResultVO().success(userService.getUserList(userDTO));
    }
}
